<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>并发——深入分析ReentrantLock的实现原理 | 博客主页 | 世界是个球，前方总有路！</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="并发">
    <meta name="description" content="一、前言&amp;emsp;&amp;emsp;之前花了点时间研究了一下并发包下的一个重要组件——抽象队列同步器AQS，在并发包中，很多的类都是基于它实现的，包括Java中常用的锁ReentrantLock。知晓了AQS的实现原理，那理解ReentrantLock的实现就非常简单了，因为它的锁功能的实现就是由AQS实现的，而它的工作仅仅是重写了一些AQS中的相关方法，并使用其中的模板方法进行加锁解锁。今天这篇博客">
<meta property="og:type" content="article">
<meta property="og:title" content="并发——深入分析ReentrantLock的实现原理">
<meta property="og:url" content="http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="博客主页">
<meta property="og:description" content="一、前言&amp;emsp;&amp;emsp;之前花了点时间研究了一下并发包下的一个重要组件——抽象队列同步器AQS，在并发包中，很多的类都是基于它实现的，包括Java中常用的锁ReentrantLock。知晓了AQS的实现原理，那理解ReentrantLock的实现就非常简单了，因为它的锁功能的实现就是由AQS实现的，而它的工作仅仅是重写了一些AQS中的相关方法，并使用其中的模板方法进行加锁解锁。今天这篇博客">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-12T07:16:43.000Z">
<meta property="article:modified_time" content="2020-04-12T20:14:31.881Z">
<meta property="article:author" content="特务依昂">
<meta property="article:tag" content="并发">
<meta name="twitter:card" content="summary">
    
        <link rel="alternate" type="application/atom+xml" title="博客主页" href="/blog/atom.xml">
    
    <link rel="shortcut icon" href="/blog/img/title.png">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

<meta name="generator" content="Hexo 4.2.0"></head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/brand.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">特务依昂</h5>
          <a href="mailto:1131564805@qq.com" title="1131564805@qq.com" class="mail">1131564805@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                博客
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/tewuyiang" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/u/5516635708/" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.cnblogs.com/tuyang1129/" target="_blank" >
                <i class="icon icon-lg icon-link"></i>
                博客园
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">并发——深入分析ReentrantLock的实现原理</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">并发——深入分析ReentrantLock的实现原理</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-04-12T07:16:43.000Z" itemprop="datePublished" class="page-time">
  2020-04-12
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E5%B9%B6%E5%8F%91/">并发</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#一、前言"><span class="post-toc-number">1.</span> <span class="post-toc-text">一、前言</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#二、正文"><span class="post-toc-number">2.</span> <span class="post-toc-text">二、正文</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-1-抽象队列同步器AQS"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">2.1 抽象队列同步器AQS</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-2-ReentrantLock的实现原理"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">2.2 ReentrantLock的实现原理</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-3-Sync类源码解析"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">2.3 Sync类源码解析</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-4-NonfairSync类源码解析"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">2.4 NonfairSync类源码解析</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-5-FairSync类源码解析"><span class="post-toc-number">2.5.</span> <span class="post-toc-text">2.5 FairSync类源码解析</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-6-ReentrantLock的成员属性与构造方法"><span class="post-toc-number">2.6.</span> <span class="post-toc-text">2.6 ReentrantLock的成员属性与构造方法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-7-ReentrantLock的加锁与解锁"><span class="post-toc-number">2.7.</span> <span class="post-toc-text">2.7 ReentrantLock的加锁与解锁</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#三、总结"><span class="post-toc-number">3.</span> <span class="post-toc-text">三、总结</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#四、参考"><span class="post-toc-number">4.</span> <span class="post-toc-text">四、参考</span></a></li></ol>
        </nav>
    </aside>


<article id="post-并发——深入分析ReentrantLock的实现原理"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">并发——深入分析ReentrantLock的实现原理</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-04-12 15:16:43" datetime="2020-04-12T07:16:43.000Z"  itemprop="datePublished">2020-04-12</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E5%B9%B6%E5%8F%91/">并发</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="一、前言"><a href="#一、前言" class="headerlink" title="一、前言"></a>一、前言</h1><p>&emsp;&emsp;之前花了点时间研究了一下并发包下的一个重要组件——抽象队列同步器<code>AQS</code>，在并发包中，很多的类都是基于它实现的，包括<code>Java</code>中常用的锁<code>ReentrantLock</code>。知晓了<code>AQS</code>的实现原理，那理解<code>ReentrantLock</code>的实现就非常简单了，因为它的锁功能的实现就是由<code>AQS</code>实现的，而它的工作仅仅是重写了一些<code>AQS</code>中的相关方法，并使用其中的模板方法进行加锁解锁。今天这篇博客就来从源码的角度分析一下<code>ReentrantLock</code>的实现。</p>
<br>

<h1 id="二、正文"><a href="#二、正文" class="headerlink" title="二、正文"></a>二、正文</h1><h2 id="2-1-抽象队列同步器AQS"><a href="#2-1-抽象队列同步器AQS" class="headerlink" title="2.1 抽象队列同步器AQS"></a>2.1 抽象队列同步器AQS</h2><p>&emsp;&emsp;在说<code>ReentrantLock</code>前，必须要先提一下<code>AQS</code>。<code>AQS</code>全称抽象队列同步器（AbstractQuenedSynchronizer），它是一个可以用来实现线程同步的基础框架。当然，它不是我们理解的<code>Spring</code>这种框架，它是一个类，类名就是<code>AbstractQuenedSynchronizer</code>，如果我们想要实现一个能够完成线程同步的锁或者类似的同步组件，就可以在使用<code>AQS</code>来实现，因为它封装了线程同步的方式，我们在自己的类中使用它，就可以很方便的实现一个我们自己的锁。</p>
<p>&emsp;&emsp;<code>AQS</code>的实现相对复杂，无法通过短短的几句话将其说清楚，我之前专门写过一篇分析<code>AQS</code>实现原理的博客：<a href="https://www.cnblogs.com/tuyang1129/p/12670014.html" target="_blank" rel="noopener">并发——抽象队列同步器AQS的实现原理</a>。</p>
<p>&emsp;&emsp;<strong>在阅读下面的内容前，请一定要先学习AQS的实现原理</strong>，因为<code>ReentrantLock</code>的实现非常简单，完全就是依赖于<code>AQS</code>的，所以我以下的描述均建立在已经理解<code>AQS</code>的基础之上。可以阅读上面推荐博客，也可以自己去查阅相关资料。</p>
<br>

<h2 id="2-2-ReentrantLock的实现原理"><a href="#2-2-ReentrantLock的实现原理" class="headerlink" title="2.2 ReentrantLock的实现原理"></a>2.2 ReentrantLock的实现原理</h2><p>&emsp;&emsp;我们先简单介绍一下<code>ReentrantLock</code>的实现原理，这样方便我们下面阅读它的源码。前面也说过，<code>ReentrantLock</code>基于<code>AQS</code>实现，<code>AQS</code>的<strong>模板方法</strong><code>acquire</code>，<code>release</code>等，已经实现了加锁和解锁的操作，而使用它的类只需要重写这些模板方法中调用的方法，比如<code>tryAcquire</code>，<code>tryRelease</code>等，这些方法通过修改<code>AQS</code>的同步状态<code>state</code>来加锁解锁。<code>AQS</code>的同步状态<code>state</code>是一个<code>int</code>类型的值，根据不同的值，就可以判断当前锁的状态，同时修改这个值就是加锁和解锁的方式。</p>
<p>&emsp;&emsp;使用<code>AQS</code>的一般方式是以内部类的形式继承<code>AQS</code>，<code>ReentrantLock</code>也是这么实现的，在它的内部，有三个<code>AQS</code>的派生类：</p>
<ol>
<li>首先第一个派生类名字叫做<strong>Sync</strong>，这是一个抽象类，直接继承自<code>AQS</code>，其中定义了一些通用的方法；</li>
<li>第二个派生类名字叫做<strong>NonfairSync</strong>，它继承自<code>Sync</code>，实现的是一种<strong>非公平锁</strong>；</li>
<li>第三个派生类名字叫<strong>FairSync</strong>，它也继承自<code>Sync</code>，实现的是一种<strong>公平锁</strong>；</li>
</ol>
<p>&emsp;&emsp;<code>ReentrantLock</code>就是通过<code>NonfairSync</code>对象或者<code>FairSync</code>对象来保证进行线程同步的。而这三个类中编写的方法，实际上就是修改同步状态的方式。当<code>state</code>的值为<code>0</code>时，表示当前并没有线程获取锁，而每获取一次锁，<code>state</code>的值就会<code>+1</code>，释放一次锁，<code>state</code>就<code>-1</code>。下面我们就通过这三个类的源码来具体看一看吧。</p>
<br>

<h2 id="2-3-Sync类源码解析"><a href="#2-3-Sync类源码解析" class="headerlink" title="2.3 Sync类源码解析"></a>2.3 Sync类源码解析</h2><p>&emsp;&emsp;我们直接来看看<code>Sync</code>类中的方法吧，Sync类中的方法不少，我只拿出其中比较重要的几个来讲一讲：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Sync</span> <span class="keyword">extends</span> <span class="title">AbstractQueuedSynchronizer</span> </span>&#123;</span><br><span class="line">	<span class="comment">/** 定义一个加锁的抽象方法，由子类实现 */</span></span><br><span class="line">    <span class="function"><span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 此方法的作用是以非公平的方式尝试获取一次锁，获取成功则返回true，否则返回false；</span></span><br><span class="line"><span class="comment">     * 需要注意，AQS的获取锁，实际上就是修改同步状态state的值。</span></span><br><span class="line"><span class="comment">     * 这里有个疑惑，既然是非公平地获取锁，那这个方法为什么不写在NonfairSync类中？</span></span><br><span class="line"><span class="comment">     * 因为ReentrantLock有一个方法tryLock，即尝试获取一次锁，调用tryLock方法时，</span></span><br><span class="line"><span class="comment">     * 无论使用的是公平锁还是非公平锁，实际上都需要尝试获取一次锁，也就是调用这个方法，</span></span><br><span class="line"><span class="comment">     * 所以这个方法定义在了父类Sync中</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">nonfairTryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 获取当前正在运行的线程</span></span><br><span class="line">        <span class="keyword">final</span> Thread current = Thread.currentThread();</span><br><span class="line">        <span class="comment">// 获取同步状态state的值，state定义在父类AQS中，</span></span><br><span class="line">        <span class="keyword">int</span> c = getState();</span><br><span class="line">        <span class="comment">// 若当前state的值为0，表示还没有线程获取锁，于是当前线程可以尝试获取锁</span></span><br><span class="line">        <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// compareAndSetState方法通过CAS的方式修改state的值，</span></span><br><span class="line">            <span class="comment">// 实际上就是让state从0变为1，因为acquires的值就是1，</span></span><br><span class="line">            <span class="comment">// 每次有线程获取了锁时，同步状态就+1</span></span><br><span class="line">            <span class="keyword">if</span> (compareAndSetState(<span class="number">0</span>, acquires)) &#123;</span><br><span class="line">                <span class="comment">// 若compareAndSetState方法返回true，表示修改state成功，</span></span><br><span class="line">                <span class="comment">// 则调用setExclusiveOwnerThread方法将当前线程记录为占用锁的线程</span></span><br><span class="line">                setExclusiveOwnerThread(current);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 若以上c == 0不满足，则表示已经有线程获取锁了，</span></span><br><span class="line">        <span class="comment">// 于是调用getExclusiveOwnerThread方法获取当前正在占用锁的线程，</span></span><br><span class="line">        <span class="comment">// 然后和当前线程比较，若当前线程就是占用锁的线程，则当前线程不会被阻塞，</span></span><br><span class="line">        <span class="comment">// 可以再次获取锁，从这里可以看出，ReentrantLock是一个可重入锁</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (current == getExclusiveOwnerThread()) &#123;</span><br><span class="line">            <span class="comment">// 计算当前线程获取锁后，state的值应该是多少，实际上就是让state + 1</span></span><br><span class="line">            <span class="keyword">int</span> nextc = c + acquires;</span><br><span class="line">            <span class="comment">// 如果nextc小于0，则保存，因为理论上同步状态是不可能小于0的</span></span><br><span class="line">            <span class="keyword">if</span> (nextc &lt; <span class="number">0</span>) <span class="comment">// overflow</span></span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Maximum lock count exceeded"</span>);</span><br><span class="line">            <span class="comment">// 使用上面计算出的nextc更新state的值，这里需要注意一点</span></span><br><span class="line">            <span class="comment">// setState不像compareAndSetState方法，setState方法并不保证操作的原子性</span></span><br><span class="line">            <span class="comment">// 这里不需要保证原子性，因为这里线程已经获取了锁，所以不会有其他线程进行操作</span></span><br><span class="line">            setState(nextc);</span><br><span class="line">            <span class="comment">// 返回true表示加锁成功</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 若以上条件均不满足，表示有其他线程获取了锁，当前线程获取锁失败</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 此方法是的作用是尝试释放锁，其实也就是让state的值-1</span></span><br><span class="line"><span class="comment">     * 这个方法是一个通用的方法，不论使用的是公平锁还是非公平锁</span></span><br><span class="line"><span class="comment">     * 释放锁时都是调用此方法修改同步状态</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">tryRelease</span><span class="params">(<span class="keyword">int</span> releases)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// getState方法获取state的值，并与参数相减，计算释放锁后state的值</span></span><br><span class="line">        <span class="comment">// 在ReentrantLock中其实就是-1</span></span><br><span class="line">        <span class="keyword">int</span> c = getState() - releases;</span><br><span class="line">		<span class="comment">// 判断当前线程是不是占用锁的线程，若不是则抛出异常</span></span><br><span class="line">        <span class="comment">// 因为只有占用了锁的线程才可以释放锁</span></span><br><span class="line">        <span class="keyword">if</span> (Thread.currentThread() != getExclusiveOwnerThread())</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalMonitorStateException();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 变量free用来标记锁释放真正的被释放，因为ReentranLock是一个重入锁</span></span><br><span class="line">        <span class="comment">// 获取锁的线程可以多次获取锁，只有每一次获取都释放，锁才是真正的释放</span></span><br><span class="line">        <span class="keyword">boolean</span> free = <span class="keyword">false</span>;</span><br><span class="line">        <span class="comment">// 判断c的值是否是0，只有c的值是0，也就是state的值为0时</span></span><br><span class="line">        <span class="comment">// 才说明当前的线程在这次释放锁后，锁真正的处于没有被使用的状态</span></span><br><span class="line">        <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// 若满足此条件，则free标记为true，表示锁真的被释放了</span></span><br><span class="line">            free = <span class="keyword">true</span>;</span><br><span class="line">            <span class="comment">// 然后标记当前占用锁的线程为null，也就是没有线程占用锁</span></span><br><span class="line">            setExclusiveOwnerThread(<span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 将c的值更新同步状态state</span></span><br><span class="line">        setState(c);</span><br><span class="line">        <span class="keyword">return</span> free;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="comment">/** 此方法判断当前线程是不是获取锁的线程 */</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">isHeldExclusively</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// getExclusiveOwnerThread方法返回当前正在占用锁的线程</span></span><br><span class="line">        <span class="comment">// 于当前的运行的线程进行比较</span></span><br><span class="line">        <span class="keyword">return</span> getExclusiveOwnerThread() == Thread.currentThread();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;以上就是<code>Sync</code>类的实现。其实<code>Sync</code>中的方法不仅仅只有上面这几个，但是剩下的那些方法都是一些零零碎碎，对我们理解<code>ReentrantLock</code>没有太大帮助的方法，所以这里就不一一列举了。从上面的方法实现中，我们可以知道以下信息：<strong>线程获取锁的方式实际上就是让同步状态state的值增加，而释放锁的方式就是让state的值减小；而且ReentrantLock实现的是可重入锁，已经获取锁的线程可以不受阻碍地再次获取锁，state的值可以不断增加，而释放锁时，只有state的值减小为0，锁才是真正被释放</strong>。</p>
<br>

<h2 id="2-4-NonfairSync类源码解析"><a href="#2-4-NonfairSync类源码解析" class="headerlink" title="2.4 NonfairSync类源码解析"></a>2.4 NonfairSync类源码解析</h2><p>下面我们再看看第二个内部类<code>NonfairSync</code>，它实现的是<strong>非公平锁</strong>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此类继承自Sync，它实现的是非公平锁</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">NonfairSync</span> <span class="keyword">extends</span> <span class="title">Sync</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">7316153563782823691L</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 在父类Sync中定义的lock方法，在子类中实现</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 调用compareAndSetState方法，企图使用CAS机制将state的值从0修改为1</span></span><br><span class="line">        <span class="comment">// 若state的值不为0，表示锁已经被其他线程获取了，则当前线程将获取锁失败</span></span><br><span class="line">        <span class="comment">// 或者state的值一开始是0，但是在当前线程修改的过程中，被其他线程修改了，</span></span><br><span class="line">        <span class="comment">// 也会返回false。若修改state失败，则就需要执行下面的acquire方法</span></span><br><span class="line">        <span class="keyword">if</span> (compareAndSetState(<span class="number">0</span>, <span class="number">1</span>))</span><br><span class="line">            setExclusiveOwnerThread(Thread.currentThread());</span><br><span class="line">        <span class="comment">// acquire方法是AQS定义的模板方法，这个方法会调用tryAcquire尝试获取锁，</span></span><br><span class="line">        <span class="comment">// 而tryAcquire方法是由子类实现的，也就是下面那个方法；</span></span><br><span class="line">        <span class="comment">// 若调用tryAcquire获取锁失败，则AQS会将线程封装成一个节点Node</span></span><br><span class="line">        <span class="comment">// 丢入AQS的同步队列中排队（这个具体实现请参考AQS的实现博客）</span></span><br><span class="line">        <span class="comment">// 归根到底，这个方法就是让线程获取锁，不断尝试，直到成功为止.</span></span><br><span class="line">        <span class="comment">// 注意这里传入的参数是1，表示加锁实际上就是让state的值+1</span></span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            acquire(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">    <span class="comment">/** </span></span><br><span class="line"><span class="comment">     * 此方法tryAcquire在AQS的模板方法中被调用，它的作用就是尝试获取一次锁，</span></span><br><span class="line"><span class="comment">     * 也就是尝试修改一次同步状态state；</span></span><br><span class="line"><span class="comment">     * 不同的实现类根据不同的需求重写tryAcquire方法，就可以按自己的意愿控制加锁的方式</span></span><br><span class="line"><span class="comment">     * AQS就是通过这种方式来提供给其他类使用的</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">tryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 此处直接调用了父类Sync中，非公平地获取一次锁的nonfairTryAcquire方法</span></span><br><span class="line">        <span class="keyword">return</span> nonfairTryAcquire(acquires);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> &emsp;&emsp;上面就是<code>NonfairSync</code>类完整的代码，并没有删减，可以看出，非常的简短。实现了<code>Sync</code>类中定义的<code>lock</code>方法，同时重写了<code>tryAcquire</code>方法，供<code>AQS</code>的模板方法<code>acquire</code>调用，且<code>tryAcquire</code>的实现仅仅是调用了<code>Sync</code>中的<code>nonfairTryAcquire</code>方法。为了有助于我们理解，我们还是来看看<code>AQS</code>中<code>acquire</code>方法的代码吧：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">acquire</span><span class="params">(<span class="keyword">int</span> arg)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 这里首先调用tryAcquire方法尝试获取一次锁，在AQS中这个方法没有实现，</span></span><br><span class="line">    <span class="comment">// 而具体实现是在子类中，也就是调用的是NonfairSync的tryAcquire方法，</span></span><br><span class="line">    <span class="comment">// 若方法返回true，表示成功获取到锁，于是后面代码都不会执行了，</span></span><br><span class="line">    <span class="comment">// 否则，将先执行addWaiter方法，这个方法的作用是将当前线程封装成为一个Node节点，</span></span><br><span class="line">    <span class="comment">// 加入到AQS的同步队列的尾部，同时将返回这个Node节点，并传入acquireQueued方法</span></span><br><span class="line">    <span class="comment">// acquireQueued方法的作用就是让当前线程阻塞，直到成功获取到锁才会从这个方法返回</span></span><br><span class="line">    <span class="comment">// acquireQueued会返回这个线程在等待的过程中是否被中断，若被中断，</span></span><br><span class="line">    <span class="comment">// 则调用selfInterrupt方法真正执行中断。</span></span><br><span class="line">    <span class="keyword">if</span> (!tryAcquire(arg) &amp;&amp;</span><br><span class="line">        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))</span><br><span class="line">        selfInterrupt();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;为什么说<code>NonfairSync</code>是非公平锁？我们可以看到，在<code>NonfairSync</code>的<code>lock</code>方法中，一个线程尝试去获取锁前，并不会判断在它之前是否有线程正在等待获取锁，而是直接尝试调用<code>compareAndSetState</code>方法获取一次锁，若获取失败，进入<code>acquire</code>方法，在这个方法中又会调用<code>tryAcquire</code>方法获取一次锁。此时若再次获取失败，才会进行进入同步队列中排队，这个过程中插了两次队，所以<code>NonfairSync</code>是非公平锁。</p>
<br>

<h2 id="2-5-FairSync类源码解析"><a href="#2-5-FairSync类源码解析" class="headerlink" title="2.5 FairSync类源码解析"></a>2.5 FairSync类源码解析</h2><p>&emsp;&emsp;下面我们来看看最后一个内部类<code>FairSync</code>，它实现的是<strong>公平锁</strong>，也就是线程按照先来后到的顺序获取锁，而不会插队：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">FairSync</span> <span class="keyword">extends</span> <span class="title">Sync</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = -<span class="number">3000897897090466540L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** 实现父类的lock方法，加锁 */</span></span><br><span class="line">    <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 直接调用AQS的模板方法acquire进行加锁，调用这个方法后，线程若没有获取锁</span></span><br><span class="line">        <span class="comment">// 则会被阻塞，直到获取了锁后才会返回。这里需要注意一点，和NonfairSync中的lock不同</span></span><br><span class="line">        <span class="comment">// 这里直接调用acquire，而不会先调用一次compareAndSetState方法获取锁</span></span><br><span class="line">        <span class="comment">// 因为FairSync是公平锁，所以不会执行这种插队的操作.</span></span><br><span class="line">        <span class="comment">// 注意这里传入的参数是1，表示加锁实际上就是让state的值+1</span></span><br><span class="line">        acquire(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** </span></span><br><span class="line"><span class="comment">     * 和NonfairSync一样，重写AQS的tryAcquire方法，若使用的是FairSync，</span></span><br><span class="line"><span class="comment">     * 则acquire中将调用此tryAcquire方法，尝试获取一次锁</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">tryAcquire</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 首先获取当前正在执行的线程</span></span><br><span class="line">        <span class="keyword">final</span> Thread current = Thread.currentThread();</span><br><span class="line">        <span class="comment">// 记录同步状态</span></span><br><span class="line">        <span class="keyword">int</span> c = getState();</span><br><span class="line">        <span class="comment">// 若state的值为0，表示现在没有线程占用了锁，于是当前线程可以尝试获取锁</span></span><br><span class="line">        <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// 尝试获取锁前，先调用hasQueuedPredecessors方法，这个方法是判断</span></span><br><span class="line">            <span class="comment">// 是否有其他线程正在排队尝试获取锁，若有，方法将返回true，那为了公平性，</span></span><br><span class="line">            <span class="comment">// 当前线程不能获取锁，于是直接结束，否则调用compareAndSetState修改state</span></span><br><span class="line">            <span class="comment">// 若修改成功，调用setExclusiveOwnerThread方法将自己设置为当前占用锁的线程</span></span><br><span class="line">            <span class="keyword">if</span> (!hasQueuedPredecessors() &amp;&amp;</span><br><span class="line">                compareAndSetState(<span class="number">0</span>, acquires)) &#123;</span><br><span class="line">                setExclusiveOwnerThread(current);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 若state不等于0，则表示当前锁已经被线程占用，那此处判断占用锁的线程是否是自己</span></span><br><span class="line">        <span class="comment">// 若是，则当前线程可以再次获取锁，因为ReentrantLock实现的是可重入锁，</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (current == getExclusiveOwnerThread()) &#123;</span><br><span class="line">            <span class="comment">// 计算当前线程再次获取锁后，state的值将变为多少，此处实际上就是 + 1</span></span><br><span class="line">            <span class="keyword">int</span> nextc = c + acquires;</span><br><span class="line">            <span class="comment">// 理论上state的值不可能小于0，于是若小于0，就报错</span></span><br><span class="line">            <span class="keyword">if</span> (nextc &lt; <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Maximum lock count exceeded"</span>);</span><br><span class="line">            <span class="comment">// 修改state的值为上面计算的新值，此处不需要CAS操作保证原子性，</span></span><br><span class="line">            <span class="comment">// 因为当前线程已经获取了锁，那其他线程就不能修改state，所以这里可以放心修改</span></span><br><span class="line">            setState(nextc);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 若以上条件均不满足，表示有其他线程占用了锁，则直接返回false</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;<code>FairSync</code>的实现也比较简单。值得注意的是，<strong>因为FairSync实现的是公平锁，所以线程获取锁前，会先判断是否有在它之前尝试获取锁的线程在排队，若有，则当前线程不能插队，也需要进行排队，并且排在那些线程之后</strong>。</p>
<br>

<h2 id="2-6-ReentrantLock的成员属性与构造方法"><a href="#2-6-ReentrantLock的成员属性与构造方法" class="headerlink" title="2.6 ReentrantLock的成员属性与构造方法"></a>2.6 ReentrantLock的成员属性与构造方法</h2><p>&emsp;&emsp;看完了内部类，下面就正式来看一看<code>ReentrantLock</code>是如何操作的吧，首先看一看它的成员属性和构造方法构造方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 记录使用的锁对象 */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Sync sync;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 默认构造方法，初始化锁对象，默认使用非公平锁 */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ReentrantLock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    sync = <span class="keyword">new</span> NonfairSync();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 参数为boolean类型的构造方法，若为false，使用非公平锁，否则使用公平锁 */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ReentrantLock</span><span class="params">(<span class="keyword">boolean</span> fair)</span> </span>&#123;</span><br><span class="line">    sync = fair ? <span class="keyword">new</span> FairSync() : <span class="keyword">new</span> NonfairSync();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h2 id="2-7-ReentrantLock的加锁与解锁"><a href="#2-7-ReentrantLock的加锁与解锁" class="headerlink" title="2.7 ReentrantLock的加锁与解锁"></a>2.7 ReentrantLock的加锁与解锁</h2><p>&emsp;&emsp;下面我就来看看<code>ReentrantLock</code>最重要的两个操作，加锁和解锁。</p>
<p><strong>（1）获取锁的方法实现</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment"> * 此方法让当前线程获取锁，若获取失败，线程将阻塞，直到获取成功为止 </span></span><br><span class="line"><span class="comment"> * 此方法不会响应中断，也就是在没有获取锁前，将无法退出</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 直接调用锁对象的lock方法，也就是之前分析的内部类中的lock方法</span></span><br><span class="line">    sync.lock();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此方法获取锁，和上面的方法类似，唯一的不同就是，调用这个方法获取锁时，</span></span><br><span class="line"><span class="comment"> * 若线程被阻塞，可以响应中断</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">lockInterruptibly</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    <span class="comment">// 调用sync对象的acquireInterruptibly方法，这个方法定义在AQS中，</span></span><br><span class="line">    <span class="comment">// 也是AQS提供给子类的一个模板方法，内部也是通过tryAcquire获取锁，</span></span><br><span class="line">    <span class="comment">// 若获取失败，线程将被阻塞，但是此方法会检测中断信号，</span></span><br><span class="line">    <span class="comment">// 若检测到中断，将通过抛出异常的方式退出阻塞</span></span><br><span class="line">    <span class="comment">// 关于这个方法的具体实现，可以去参考AQS的相关博客，此处就不展开描述了</span></span><br><span class="line">    sync.acquireInterruptibly(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment"> * 调用此方法尝试获取一次锁，不论成功失败，都会直接返回</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 此处直接调用Sync类中的nonfairTryAcquire方法，</span></span><br><span class="line">    <span class="comment">// 这也就是为什么nonfairTryAcquire定义在父类Sync中，</span></span><br><span class="line">    <span class="comment">// 因为不论是使用公平锁还是非公平锁，都需要在此处调用这个方法</span></span><br><span class="line">    <span class="keyword">return</span> sync.nonfairTryAcquire(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<p><strong>（2）是否锁的方法实现</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此方法用来释放锁</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">unlock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 此处调用的是AQS的release方法，这个方法也是AQS提供的一个模板方法，</span></span><br><span class="line">    <span class="comment">// 在这个方法中，将调用子类重写的tryRelease方法尝试释放锁，若释放成功</span></span><br><span class="line">    <span class="comment">// 则会唤醒等待队列中的下一个线程，让它停止阻塞，开始尝试获取锁，</span></span><br><span class="line">    <span class="comment">// 关于这个方法的具体实现，可以参考我之前推荐的AQS源码分析博客。</span></span><br><span class="line">    <span class="comment">// 这里需要注意，传入的参数是1，表明释放锁实际上就是让state的值-1</span></span><br><span class="line">    sync.release(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;以上就是<code>ReentrantLock</code>加锁和解锁的方法，出乎意料，非常的简单，每个方法都只有一句代码，调用<code>AQS</code>类中提供的模板方法。这就是<code>AQS</code>的好处，<code>AQS</code>封装了线程同步的代码，我们只需要在类中使用它，就能很简单的实现一个锁。所以我前面才说，在看<code>ReentrantLock</code>前，一定要先学习<code>AQS</code>，理解了<code>AQS</code>，理解<code>ReentrantLock</code>就完全没有难度了。</p>
<p>&emsp;&emsp;上面这些就是<code>ReentrantLock</code>中的关键方法，其实除了这些方法之外，还有许多其他的方法，但是那些方法并不是关键，实现也都非常简单，基本上就是一句代码，可以自己直接去阅读源码，我这里就不一一列举了。</p>
<br>

<h1 id="三、总结"><a href="#三、总结" class="headerlink" title="三、总结"></a>三、总结</h1><p>&emsp;&emsp;经过上面的分析，我们会发现，<code>ReentrantLock</code>的实现原理非常的简单，因为它是基于<code>AQS</code>实现的，复杂性都被封装在了<code>AQS</code>中，<code>ReentrantLock</code>仅仅是它的使用者，所以，学习<code>ReentrantLock</code>实际上就是学习<code>AQS</code>。<code>AQS</code>是<code>Java</code>并发中的重要组件，很多的类都是基于它实现的，比如非常常用的<code>CountDownLatch</code>。<code>AQS</code>也是面试中的常考题，所以一定要好好研究。此处再次推荐我写的<code>AQS</code>解析博客：<a href="https://www.cnblogs.com/tuyang1129/p/12670014.html" target="_blank" rel="noopener">并发——抽象队列同步器AQS的实现原理</a>。</p>
<br>

<h1 id="四、参考"><a href="#四、参考" class="headerlink" title="四、参考"></a>四、参考</h1><ul>
<li>JDK1.8源码</li>
</ul>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-04-12T20:14:31.881Z" itemprop="dateUpdated">2020-04-13 04:14:31</time>
</span><br>


        
        世界是个球，前方总有路！
        
    </div>
    
    <footer>
        <a href="http://tewuyiang.gitee.io/blog">
            <img src="/blog/img/avatar.jpg" alt="特务依昂">
            特务依昂
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/%E5%B9%B6%E5%8F%91/" rel="tag">并发</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ReentrantLock的实现原理》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ReentrantLock的实现原理》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《并发——深入分析ReentrantLock的实现原理》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">并发——深入分析CountDownLatch的实现原理</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E2%80%94%E2%80%94LinkedBlockingQueue%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">阻塞队列——LinkedBlockingQueue源码分析</h4>
      </a>
    </div>
  
</nav>



    




















</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/blog/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>特务依昂 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ReentrantLock的实现原理》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ReentrantLock的实现原理》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《并发——深入分析ReentrantLock的实现原理》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '人呢，怎么不见了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!欢迎回来!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
